// import * as express from "express";
let express = require("express");
let expressWebSocket = require("express-ws");
let WebSocket = require("websocket-stream");
let webSocketStream = require("websocket-stream/stream");
let ffmpegInstaller = require("@ffmpeg-installer/ffmpeg");
let ffmpeg = require("fluent-ffmpeg");

ffmpeg.setFfmpegPath(ffmpegInstaller.path);
function localServer() {
  let app = express();
  app.use(express.static(__dirname));
  expressWebSocket(app, null, {
    perMessageDeflate: true,
  });
  app.ws("/rtsp/", rtspRequestHandle);
  app.listen(8888);
  console.log("express listened");
}
function rtspRequestHandle(ws, req) {
  console.log("rtsp request handle");
  const stream = webSocketStream(
    ws,
    {
      binary: true,
      browserBufferTimeout: 1000000,
    },
    {
      browserBufferTimeout: 1000000,
    }
  );
  let url;
  if (req.query.cameraid) {
    url =
      req.query.url +
      `?cameraid=${req.query.cameraid}&substream=${req.query.substream}`;
  } else {
    url = req.query.url;
  }

  try {
    ffmpeg(url)
      //  RTSP 优化的参数
      .addInputOption(
        "-rtsp_transport",
        "tcp",
        "-buffer_size",
        "102400",
        "-analyzeduration",
        "100000",
        "-max_delay",
        "1000000"
      )
      // RTSP 优化的参数
      .on("start", function () {
        console.log(url, "Stream started.");
      })
      // 在线处理
      .on("codecData", function () {
        console.log(url, "Stream codecData.");
      })
      .on("error", function (err) {
        console.log(url, "An error occured: ", err.message);
      })
      // 掉线的处理
      .on("end", function () {
        console.log(url, "Stream end!");
      })
      .outputFormat("flv")
      .videoCodec("copy")
      .noAudio()
      .pipe(stream);
  } catch (error) {
    console.log(error);
  }
}
localServer();
